package com.fvision.camera.manager;

import android.media.AudioAttributes;
import android.media.AudioManager;
import android.media.MediaPlayer;
import android.media.SoundPool;
import android.os.Build;

import com.fvision.camera.App;
import com.fvision.camera.utils.LogUtils;

import java.util.HashMap;
import java.util.LinkedList;

/**
 * Created by zoulequan on 2018/7/7.
 */

public class AdasSoundManager {
    private static AdasSoundManager instance = null;
    private HashMap<Integer, Integer> mSoundMap = new HashMap<>();
    private LinkedList<Integer> soundList = new LinkedList<>();
    private int currentCmd = -1;
    public boolean isProcess = false;
    private static SoundPool soundPool;
    private static MediaPlayer mediaPlayer;
    private boolean mAudioFocus = false;

    public static AdasSoundManager getInstance() {
        if (instance == null) {
            instance = new AdasSoundManager();
            initSoundPool();
        }
        return instance;
    }

    public boolean ismAudioFocus() {
        return mAudioFocus;
    }

    public void setmAudioFocus(boolean mAudioFocus) {
        this.mAudioFocus = mAudioFocus;
    }

    public void playSound(int rawId) {
        soundList.add(rawId);
        LogUtils.write("ADAS 声音放入数组 " + soundList.size());
        if (mSoundMap.get(rawId) == null && SoundManager.getInstance().getSoundModel() == SoundManager.SOUND_POOL) {
            mSoundMap.put(rawId, soundPool.load(App.getInstance(), rawId, 1));
            soundPool.setOnLoadCompleteListener(new SoundPool.OnLoadCompleteListener() {
                @Override
                public void onLoadComplete(SoundPool soundPool, int sampleId, int status) {
                    process();
                }
            });
            return;
        }
        process();
    }

    /**
     * 适合播放声音短，文件小
     * 可以同时播放多种音频
     * 消耗资源较小
     */
    public void process() {
        LogUtils.d("soundList " + soundList.size());
        if (isProcess) {
            LogUtils.write("ADAS 正在播放声音");
            return;
        }
        if (soundList.size() == 0) {
            LogUtils.write("ADAS 播放声音结束");
            SoundManager.getInstance().setAdasIsPlaying(false);
            if (SoundManager.getInstance().getSoundModel() == SoundManager.MEDIA_PLAYER) {
                if(!SoundManager.getInstance().isEdogIsPlaying()){
                    SoundManager.getInstance().abandonAudioFocus();
                }
            }
            return;
        }
        SoundManager.getInstance().setAdasIsPlaying(true);

        isProcess = true;
        currentCmd = soundList.removeFirst();
        LogUtils.write("ADAS 从队列取出并播放 " + soundList.size());
        play(currentCmd);

//        Timer timer = new Timer();
//        timer.schedule(task, getAudioDuation(currentCmd));

        if (SoundManager.getInstance().getSoundModel() == SoundManager.getInstance().SOUND_POOL) {
            new Thread(new Runnable() {
                @Override
                public void run() {
                    try {
                        Thread.sleep(3500);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    isProcess = false;
                    process();
                }
            }).start();
        }

    }

    private void play(int cmd) {
        if (SoundManager.getInstance().getSoundModel() == SoundManager.SOUND_POOL) {
            soundPool.play(mSoundMap.get(cmd), 1, 1, 0, 0, 1);
        } else if (SoundManager.getInstance().getSoundModel() == SoundManager.MEDIA_PLAYER) {
            SoundManager.getInstance().requestAudioFocus();
            mediaPlay(cmd);
        }


        //第一个参数id，即传入池中的顺序，第二个和第三个参数为左右声道，第四个参数为优先级，第五个是否循环播放，0不循环，-1循环
        //最后一个参数播放比率，范围0.5到2，通常为1表示正常播放
//        soundPool.play(1, 1, 1, 0, 0, 1);
        //回收Pool中的资源
        //soundPool.release();
    }

    private void mediaPlay(int raw) {
        try {
            if (mediaPlayer != null) {
                mediaPlayer.stop();
                mediaPlayer.release();
                mediaPlayer = null;
            }

//            setVolumeControlStream(AudioManager.STREAM_MUSIC);
            mediaPlayer = MediaPlayer.create(App.getInstance(), raw);
            mediaPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                @Override
                public void onPrepared(MediaPlayer mp) {
                    if (mp != null) {
                        mp.start();
                    }
                }
            });
            LogUtils.write("Adas mediaPlay setOnCompletionListener");
            mediaPlayer.setOnCompletionListener(beepListener);
            mediaPlayer.prepareAsync();
            LogUtils.write("Adas mediaPlay end ");
        } catch (Exception localException) {
 //           isProcess = false;
            LogUtils.write("Adas "+localException.toString());
        }

    }

    private static void initSoundPool() {
        if (Build.VERSION.SDK_INT >= 21) {
            SoundPool.Builder builder = new SoundPool.Builder();
            //传入音频的数量
            builder.setMaxStreams(1);
            //AudioAttributes是一个封装音频各种属性的类
            AudioAttributes.Builder attrBuilder = new AudioAttributes.Builder();
            //设置音频流的合适属性
            attrBuilder.setLegacyStreamType(AudioManager.STREAM_MUSIC);
            builder.setAudioAttributes(attrBuilder.build());
            soundPool = builder.build();
        } else {
            //第一个参数是可以支持的声音数量，第二个是声音类型，第三个是声音品质
            soundPool = new SoundPool(1, AudioManager.STREAM_SYSTEM, 5);
        }
    }

    private final MediaPlayer.OnCompletionListener beepListener = new MediaPlayer.OnCompletionListener() {
        public void onCompletion(MediaPlayer mediaPlayer1) {
            //mediaPlayer.seekTo(0);
            try {
                if (mediaPlayer != null) {
                    mediaPlayer.stop();
                    mediaPlayer.release();
                    mediaPlayer = null;
                }
            }catch (Exception e){
                LogUtils.write("Adas "+e.getMessage());
            }finally {
                isProcess = false;
            }
            LogUtils.write("Adas 播放结束，继续下一条");
            process();
        }
    };

}
